package com.example.shutdown_v1.schedule;

import com.example.shutdown_v1.entity.Sensor;
import com.example.shutdown_v1.repository.SensorRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Z轴基准值更新定时任务
 * 
 * 功能: 每天凌晨更新所有IM600传感器的Z轴基准值
 * 原因: IM600每天凌晨会自动重置Z轴,需要记录新的基准值
 * 
 * 执行时间: 每天凌晨00:05执行
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(
    prefix = "schedule.yaw-baseline-update",
    name = "enabled",
    havingValue = "true",
    matchIfMissing = false  // 默认禁用，已被 DailyAutoCalibrationScheduler 取代
)
public class YawBaselineUpdateScheduler {
    
    private final SensorRepository sensorRepository;
    
    /**
     * 每天凌晨00:05更新Z轴基准值
     * 
     * 注意: 设置为00:05而不是00:00,给IM600一些时间完成自动重置
     */
    @Scheduled(cron = "${schedule.yaw-baseline-update.cron:0 5 0 * * ?}")
    public void updateYawBaseline() {
        log.info("========================================");
        log.info("[定时任务] 开始更新Z轴基准值...");
        
        try {
            // 查询所有IM600传感器
            List<Sensor> im600Sensors = sensorRepository.findAll().stream()
                    .filter(sensor -> "IM600".equals(sensor.getSensorModel()))
                    .toList();
            
            if (im600Sensors.isEmpty()) {
                log.info("[定时任务] 没有IM600传感器需要更新");
                return;
            }
            
            log.info("[定时任务] 找到 {} 个IM600传感器", im600Sensors.size());
            
            int successCount = 0;
            int failCount = 0;
            
            for (Sensor sensor : im600Sensors) {
                try {
                    // 重置基准值为0(因为IM600已经自动重置了Z轴)
                    sensor.setYawBaseline(0.0);
                    sensor.setBaselineUpdateTime(LocalDateTime.now());
                    sensorRepository.save(sensor);
                    
                    log.info("[传感器:{}] Z轴基准值已重置为0.0", sensor.getSensorId());
                    successCount++;
                    
                } catch (Exception e) {
                    log.error("[传感器:{}] 更新Z轴基准值失败: {}", 
                            sensor.getSensorId(), e.getMessage());
                    failCount++;
                }
            }
            
            log.info("========================================");
            log.info("[定时任务] Z轴基准值更新完成 - 成功: {}, 失败: {}", successCount, failCount);
            log.info("========================================");
            
        } catch (Exception e) {
            log.error("[定时任务] Z轴基准值更新任务执行失败", e);
        }
    }
    
    /**
     * 手动触发更新(用于测试或特殊情况)
     */
    public void manualUpdate() {
        log.info("[手动触发] 开始更新Z轴基准值...");
        updateYawBaseline();
    }
}

